package com.geoboard.service;

import java.util.ArrayList;

import android.os.Bundle;
import android.util.Log;

import com.geoboard.ActivityInterface;
import com.geoboard.dialogs.SelectBoardDialog;
import com.geoboard.entity.Board;
import com.geoboard.fragments.MapFrag;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.model.LatLng;

public class BrowseClickListener implements OnMapClickListener {

	private String TAG = this.getClass().getSimpleName();
	private MapFrag mMapFrag;
	
	public BrowseClickListener(MapFrag mapFrag) {
		mMapFrag = mapFrag;
	}
	
	/** add all clicked boards to a list & display list as list fragment.
	 */
	@Override
	public void onMapClick(LatLng point) {
		Log.d(TAG, "Board click registered - showing posts");
		ArrayList<Board> visibleBoards = mMapFrag.getVisibleBoards();
		ArrayList<Board> clickedBoards = new ArrayList<Board>();

		for (Board board : visibleBoards) {
			if (board.containsPoint(point))
				clickedBoards.add(board);
		}
		
		//if just one board, switch to post viewing on that board
		if (clickedBoards.size() == 1) {
			//switch to post viewing activity
			((ActivityInterface) mMapFrag.getActivity()).showPosts(clickedBoards.get(0));
		}
		else if (clickedBoards.size() > 1) {
			Bundle args = new Bundle();
			args.putParcelableArrayList("com.geoboard.entity.board", clickedBoards);
			
		    SelectBoardDialog dialogFrag = new SelectBoardDialog();
		    dialogFrag.setArguments(args);
		    dialogFrag.show(mMapFrag.getActivity().getSupportFragmentManager(), "dialogFrag");
		    
		}
	}
}
